import config from './config';
import message from './message';

async function request(options, assistOpts = {}){
	let { isLoading = true, isLogin = true} = assistOpts;

	let opts = await setOption(options);
	const [errors, response] = await uni.request(opts);
	// hideLoading && hideLoading();
	if(errors){
		errorHandle(errors);
	} else {
		return successHandle(response, opts.url);
	}
}

async function setOption(options){

	let env=__wxConfig.envVersion
	var url;
	if(['develop'].indexOf(env)===-1){
		//非开发环境时做的判断
		 url = (options.apiUrl  || config.apiUrl) + options.uri;
	}else{
		//开发环境时做的判断
		 url = (options.apiUrl  || config.apiUrl) + options.uri;
	}
	
	let header = {
        'custom-header': 'hello' //自定义请求头信息
		...options.header
	};

    let postData = options.data;
	options = {
			url,
			method: 'POST',
			...options,
			header,
			data: postData
	};
	return options;
};

const errorHandle = errors => {
	let errMsg = '未知异常', err = errors.errMsg.trim() || '';
	console.log('==========================');
	console.log(err);
	if(err.indexOf('request:fail') > -1) {
		errMsg = '网络已断开，请稍后重试';
	}
	// switch(err.indexOf('request:fail') > -1){
	// 	case 'request:fail':
	// 		errMsg = '网络已断开，请稍后重试';
	// 	break;
	// }
	message.error(errMsg);
	throw errMsg;
}

async function successHandle(response, uri) {
	if(response.statusCode == 301) {
		// 微信号未绑定
		return 'err';
	}
	if(response.statusCode == 403) {
		await store.dispatch('logout');// 清除本地token
		// auth();
		return 'err';
	}
	if('0, 200'.indexOf(response.statusCode) == -1){
		message.error('服务器开小差了');
		return 'err';
	}

	if(response.data.code!==undefined&&response.data.code!==null){
		if(response.data.code==='403'){
			// #ifndef H5
			// logout(response.data.msg);
			throw response.data.msg;
			// #endif

			// #ifdef H5
			// alert(url+'/'+JSON.stringify(response))
			console.log(location.href)
			location.href = config.userDomain + '/proxy/login?from='+location.href
			// #endif
		}
		if(response.data.code==='402'){
			return response.data;
		}
		class UnknownError {
			constructor(data){
				this.code = data.code;
				this.message = data.msg||data.message;
				this.response = data;
				console.warn(`未知异常：uri:${uri},code:${this.code},${this.message},transId:${data.transId}`);
			}
			toString(){
				console.log('this.message++++++',this.message);
				return this.message;
			}
		}
	}
	// TODO
	let result = response.data.data;
	return result
}

function post(options, assistOpts){
	return request({
		method:'POST',
		...options
	}, assistOpts || {});
}

function get(options, assistOpts){
	return request({
		method:'GET',
		...options
	}, assistOpts || {});
}

export {
	request,
	post,
	get,
}
